//
//  ReadBrightnessView.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/14.
//

import UIKit

class ReadBrightnessView: UIView {
        
    lazy var subImage: UIImageView = {
        return UIImageView()
    }()

    lazy var addImage: UIImageView = {
        return UIImageView()
    }()

    lazy var slider: WNSlider = {
        var slider = WNSlider()
        slider.minimumValue = 0
        slider.maximumValue = 1
        slider.setThumbImage(UIImage(named: "read_setting_light_slider")?.wn_resized(newSize: CGSize(width: 50, height: 50)), for: .normal)
        slider.minimumTrackTintColor = .init(named: "red_FE95B4")
        slider.maximumTrackTintColor = .init(named: "gray_ECE0E4")
        slider.backgroundColor = .clear
        slider.addTarget(self, action: #selector(sliderValurChanged(slider:event:)), for: .valueChanged)
        return slider
    }()
        
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(subImage)
        addSubview(addImage)
        addSubview(slider)
        subImage.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(12)
            make.width.height.equalTo(24)
        }
        addImage.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(-12)
            make.width.height.equalTo(24)
        }
        slider.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(CGSize(width: scaleWidth(220), height: 6))
        }
        wn_cornerWithBorder(18)
    }
    
    func darkModeConfig() {
        backgroundColor = .init(named: isDark() ? "black_1B1B1B" : "white_F9F8F8")
        slider.value = getReadConfigItem("brightness") as? Float ?? 0.0
        (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.screen.brightness = CGFloat(slider.value)
        subImage.image = UIImage(named: isDark() ? "read_setting_light_min_night" : "read_setting_light_min")
        addImage.image = UIImage(named: isDark() ? "read_setting_light_max_night" : "read_setting_light_max")
    }
    
    @objc func sliderValurChanged(slider: UISlider, event: UIEvent) {
        if let touchEvent = event.allTouches {
            for item in touchEvent {
                switch item.phase {
                case .moved, .ended:
                    saveReadConfigItem("brightness", slider.value)
                    (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.screen.brightness = CGFloat(slider.value)
                default:
                    break
                }
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
